package com.example.fang.demodruid.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Field;
import java.security.Key;
import java.security.Security;

/**
 * @Author 01410843
 * @Description  aes工具包
 * @Date 14:59 2022/6/22
 * @Param 
 * @return 
 **/
public class MrAesUtils {
    public static final String KEY_ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    public static Key toKey(byte[] key)
            throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        return secretKey;
    }

    public static byte[] encrypt(byte[] data, byte[] key)
            throws Exception {
        Key k = toKey(key);

        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", BouncyCastleProvider.PROVIDER_NAME);

        cipher.init(1, k);

        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, byte[] key)
            throws Exception {
        Key k = toKey(key);

        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(2, k);

        return cipher.doFinal(data);
    }

    static {
        Security.addProvider(new BouncyCastleProvider());

        Field localField1 = null;
        try {
            localField1 = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
            localField1.setAccessible(true);
            Field localField2 = Field.class.getDeclaredField("modifiers");
            localField2.setAccessible(true);
            localField2.setInt(localField1, localField1.getModifiers() & 0xFFFFFFEF);
            localField1.set(null, Boolean.FALSE);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
}